
//注册ua的参数
var uaConfig;

var checkStatus;//定期检查UA健康任务

var myUA=null;

var freeswitchUser = null;

var status = "notConnected";
/*
//初始化UA
$(function () {

    initSIPUA();

})
*/


//===========================================================================华丽的分割线====================================================================

/**
 * 初始化UA
 * @param myUA
 */
function initSIPUA() {
    console.log("======================initSIPUA==========================");
    if(checkStatus!=null&&checkStatus!=undefined){//看看还有没有残留的定时检测健康任务
        clearTimeout(checkStatus);
    }
        //在这里,其实targetCallPhone才是主叫号码,freeswitch会先打给targetCallPhone,再打给mainCallPhone(客户)
    uaConfig={
        // uri: targetCallPhone+"@113.108.202.236",
        uri: freeswitchUser+"@"+fsConnectWsVo.freeswitchDissUrl,
        wsServers: fsConnectWsVo.freeswitchWsUrl,
        authorizationUser: freeswitchUser,
        displayName:freeswitchUser,
        password: "ihkyanfa",
        rel100: SIP.C.supported.SUPPORTED, //这个很重要,如果不加这个参数,在直呼的方式下很可能请不到振铃音之类的
        log:{
            builtinEnabled:false
        },
        register: true,      //默认为true
        registerExpires:6000 //注册到期时间
    };


    //新建ua
    myUA = new SIP.UA(uaConfig);

    //ws链接成功调用
    myUA.on("connected", function () {
        console.log("freeswitchLog:  websocket连接成功: " + uaConfig.wsServers);
        status = "connected";
    });

//ws链接失败调用
    myUA.on("disconnected", function () {
        console.log("freeswitchLog:  websocket连接失败: " + uaConfig.wsServers);
        status = "notConnected";
    });

//注册成功调用
    myUA.on("registered", function () {
        console.log("freeswitchLog:  "+uaConfig.authorizationUser+"用户注册成功");
        status = "connected";
    });

//注册失败时候调用
    myUA.on("unregistered", function () {
        console.log("freeswitchLog:  "+uaConfig.authorizationUser+"用户取消注册");
        status = "notConnected";
    });

    /**
     * 设置定时任务,每隔20秒检测
     */
    checkStatus=setInterval("checkUAStatus()", 20000);
}

/**
 * 定时检测UA的健康,假如断开了,重新注册
 */
function checkUAStatus() {
    if(myUA!=null&&myUA!=undefined){
        var isConnected = myUA.isConnected();
        var isRegistered = myUA.isRegistered();
        if (!isConnected || !isRegistered) {
            console.log("freeswitchLog:  连接或者注册异常,将重新连接");
            myUA.start();
        }else{
            console.log("freeswitchLog:  连接和注册正常,每20秒检测一次")
        }
    }else{
        console.log("freeswitchLog:  连接或者注册异常,将重新连接");
        initSIPUA();

    }


}



function initSIP(uesrName) {
    console.log("================"+uesrName+"===============");
    freeswitchUser = uesrName;
    initSIPUA();
}
